<?php

namespace app\model;

use support\Db;
use support\Model;

class WaDepartment
{
    /**
     * The table associated with the model.
     *
     * @var string
     */
    protected $table = 'wa_department';

    /**
     * The primary key associated with the table.
     *
     * @var string
     */
    protected $primaryKey = 'id';

    /**
     * Indicates if the model should be timestamped.
     *
     * @var bool
     */
    public $timestamps = false;

    /**
     * 部门列表 - 分页
     * @return false|string
     */
    public static function list($fields,$condition)
    {
        $list = Db::table('wa_department')
            ->select($fields)
            ->where($condition)
            ->orderBy('id', 'asc')
            ->get();

        $conditionSecond = [];
        $conditionSecond []= ['pid','=',1];
        $conditionSecond []= ['status','!=',4];
        $children = Db::table('wa_department')->select($fields)->where($conditionSecond)->get();
        foreach ($children as $k){
            $secondChildren = Db::table('wa_department')->where([['pid','=', $k->id],['status','!=',4]])->get();
            if ($secondChildren){
                $k->children = $secondChildren;
            }else{
                $k->children = [];
            }
        }

        foreach (array($list) as $key){
            $list[0]->children = $children;
        }
        return json_encode($list);
    }


    /**
     *
     * 部门列表 - 不分页
     * @param $fields
     * @param $condition
     * @return false|string
     */
    public static function all($fields,$condition)
    {
        $list = Db::table('wa_department')
            ->select($fields)
            ->where($condition)
            ->get();
        return json_encode($list);
    }


    public static function find($condition)
    {
        $res = Db::table('wa_department')
            ->where($condition)
            ->first();
        return json_encode($res);
    }

    public static function created($data){

        return Db::table('wa_department')->insertGetId($data);

    }

    public static function updated($condition,$data){

        $res = Db::table('wa_department')->where($condition)->update($data);
        return json_encode($res);

    }

    public static function allList($fields,$condition)
    {
        $list = Db::table('wa_department')
            ->select($fields)
            ->where($condition)
            ->get();

        return json_encode($list);
    }
}